package crp.core.timetable.domain.services;

import com.qwlabs.lang.C2;
import crp.core.timetable.domain.models.TimetableEntity;
import crp.core.timetable.domain.models.TimetableKey;
import crp.core.timetable.domain.repositories.TimetableRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

@ApplicationScoped
public class TimetableSearcher {
    private final TimetableRepository timetableRepository;

    @Inject
    public TimetableSearcher(TimetableRepository timetableRepository) {
        this.timetableRepository = timetableRepository;
    }

    public Map<TimetableKey, TimetableEntity> fetch(Collection<TimetableKey> keys) {
        if (C2.isEmpty(keys)) {
            return Map.of();
        }
        var result = new HashMap<TimetableKey, TimetableEntity>(keys.size());
        List<TimetableEntity> timetables = timetableRepository.findByCourseIds(
                C2.list(keys, TimetableKey::getCourseId))
                .sorted(Comparator.comparing(TimetableEntity::getEndAt))
                .collect(toList());
        keys.forEach(key -> timetables.stream().filter(key::match).findFirst().ifPresent(t -> result.put(key, t)));
        return result;
    }
}
